package com.hxh.essaysharing.controller;

import com.hxh.essaysharing.common.AjaxResult;
import com.hxh.essaysharing.common.ApplicationVariable;
import com.hxh.essaysharing.common.PasswordUtils;
import com.hxh.essaysharing.common.UserSessionUtils;
import com.hxh.essaysharing.entity.Userinfo;
import com.hxh.essaysharing.entity.viewobject.UserinfoVO;
import com.hxh.essaysharing.service.ArticleService;
import com.hxh.essaysharing.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 * @date 2023/7/21 19:55
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private ArticleService articleService;

    /**
     * 注册
     */
    @RequestMapping("/reg")
    public AjaxResult reg(Userinfo userinfo) {
        // 非空校验
        if (userinfo == null || !StringUtils.hasLength(userinfo.getUsername())
            || !StringUtils.hasLength(userinfo.getPassword())
            || !StringUtils.hasLength(userinfo.getNickname())) {
            return AjaxResult.fail(-1, "非法参数");
        }
        // 对密码进行加密后存储到数据库
        userinfo.setPassword(PasswordUtils.encrypt(userinfo.getPassword()));
        // 设置创建和修改时间
        userinfo.setCreatetime(LocalDateTime.now());
        userinfo.setUpdatetime(LocalDateTime.now());
        return AjaxResult.success(userService.reg(userinfo));
    }

    /**
     * 登录
     */
    @RequestMapping("/login")
    public AjaxResult login(String username, String password, HttpServletRequest request) {
        // 非空校验
        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            return AjaxResult.fail(-1, "非法参数");
        }
        // 查询数据库
        Userinfo loginUser = userService.getUserByName(username);
        if (loginUser != null && loginUser.getId() > 0) {
            // 用户名有效, 进行密码比对
            if (PasswordUtils.decrypt(password, loginUser.getPassword())) {
                // 登录成功
                loginUser.setPassword(""); // 隐藏敏感信息
                // 将用户存储到 session
                HttpSession session = request.getSession(true);
                session.setAttribute(ApplicationVariable.USER_SESSION_KEY, loginUser);
                return AjaxResult.success(true);
            }
        }
        // 登录失败
        return AjaxResult.success(0, false);
    }

    /**
     * 加载个人信息
     */
    @RequestMapping("/showinfo")
    public AjaxResult showInfo(HttpServletRequest request) {
        UserinfoVO userinfoVO = new UserinfoVO();
        // 得到当前登录用户
        Userinfo loginUser = UserSessionUtils.getSessUser(request);
        if (loginUser == null) {
            return AjaxResult.fail(-1, "非法请求");
        }
        // Spring 提供的深克隆方法
        BeanUtils.copyProperties(loginUser, userinfoVO);
        // 通过 uid 得到用户发表文章的总数
        userinfoVO.setArtCount(articleService.getArtCountByUid(loginUser.getId()));
        // 通过 uid 得到用户总访问量信息
        Integer allReadCount = articleService.getAllReadCountByUid(loginUser.getId());
        userinfoVO.setAllReadCount(allReadCount == null ? 0 : allReadCount);
        // 通过 uid 得到用户总草稿数量的信息
        userinfoVO.setDraftCount(articleService.getDraftCountByUid(loginUser.getId()));
        return AjaxResult.success(userinfoVO);
    }

    /**
     * 注销
     */
    @RequestMapping("/logout")
    public AjaxResult logout(HttpSession session) {
        if (session != null) {
            session.removeAttribute(ApplicationVariable.USER_SESSION_KEY);
        }
        return AjaxResult.success(true);
    }

    /**
     * 加载作者信息
     */
    @RequestMapping("/getuserbyid")
    public AjaxResult getUserById(Integer id) {
        if (id == null || id <= 0) {
            return AjaxResult.fail(-1, "非法参数");
        }
        // 获取作者信息
        Userinfo user = userService.getUserById(id);
        if (user == null || user.getId() <= 0) {
            return AjaxResult.fail(-1, "非法参数");
        }
        user.setPassword(""); // 去除敏感数据
        UserinfoVO userinfoVO = new UserinfoVO();
        BeanUtils.copyProperties(user, userinfoVO);
        // 查询发表文章数量
        userinfoVO.setArtCount(articleService.getArtCountByUid(id));
        // 查询访问量
        userinfoVO.setAllReadCount(articleService.getAllReadCountByUid(id));
        return AjaxResult.success(userinfoVO);
    }
}
